<?php
if (!defined("__WD__")) exit("Wrong Connect");

class Model_Bbs extends __Model {

	private $settings = null;

	private $user = null;
	
	function __construct() {

		parent::__construct();

		// Loader
		$this->load->module("input", $this->input);
		$this->load->module("mysql", $this->db);

		$this->load->model("admin/member", $this->member);
		$this->load->model("admin/admin", $this->admin);
		
		// Default
		$this->settings = array(
			"len_line" => 20,
			"len_page" => 7
			// 2.0 에서는 skin 포함. useBoard("qna", array( 'skin' => 'admin/bbs/skin/default' ) ); 이런식으로 사용할수 있게.
		);
		$this->user = $this->member->getMember();
		if ( isset($this->user) ) {
			$this->user['groups'] = explode(",", $this->user['groups']);
		}
		// Global Data
		$this->data->make("bbs");
	}
	function _checkGrant( $type, $grant ) {

		$u_groups = (!isset($this->user['groups']))?array():$this->user['groups'];

		$auth = ( isset($grant[$type]) && $grant[$type] != "" )? $grant[$type] : array() ;
		
		if ( in_array(0, $auth) ) return true;		

		$result = array_intersect( $auth , $u_groups );

		if ( count($result) > 0 ) return true;
		
		return false;		
		
	}
	function _getBoard( $id ) {
		
		$result = $this->db->result("select `grant` from `wd_board` where `id`=?", array($id));

		$this->data->bbs->id		= $id;
		$this->data->bbs->name		= $result['name'];

		// category
		$category_list = $this->db->fetch_assoc("select `idx`, `name` from `wd_category` where `board_id`=?", array($id));
		foreach( $category_list as $v )  $this->data->bbs->category[ $v['idx'] ] = $v['name'];

		$this->data->bbs->reg_date	= $result['reg_date'];
		$this->data->bbs->mod_date	= $result['mod_date'];

		
		$this->data->bbs->is_list	= false;
		$this->data->bbs->is_view	= false;
		$this->data->bbs->is_modify	= false;
		$this->data->bbs->is_delete	= false;
		$this->data->bbs->is_write	= false;
		$this->data->bbs->is_secret	= false;

		$this->data->bbs->is_commentwrite	= false;
		$this->data->bbs->is_commentdelete	= false;

		$grant = _unserialize( $result['grant'] );
		
		$this->data->bbs->is_list	= $this->_checkGrant( "list", $grant );
		$this->data->bbs->is_view	= $this->_checkGrant( "view", $grant );;
		$this->data->bbs->is_modify	= $this->_checkGrant( "modify", $grant );;
		$this->data->bbs->is_delete	= $this->_checkGrant( "delete", $grant );;
		$this->data->bbs->is_write	= $this->_checkGrant( "write", $grant );;
		$this->data->bbs->is_secret	= $this->_checkGrant( "secret", $grant );;

		$this->data->bbs->is_commentwrite	= $this->_checkGrant( "commentwrite", $grant );;
		$this->data->bbs->is_commentdelete	= $this->_checkGrant( "commentdelete", $grant );;

	}
	
	function _hitArticle( $idx ) {
		// hit!
		if ( !isset($_SESSION['wd_bbs_recent_idx']) ) $_SESSION['wd_bbs_recent_idx'] = $idx;
		if ($_SESSION['wd_bbs_recent_idx'] != $idx ) {
			$_SESSION['wd_bbs_recent_idx'] = $idx;
			$this->db->query("update `wd_data` set `hit`=`hit`+1 where `idx`=?", array($idx));
		}
	}
	
	function _getArticle( $idx ) {
		$result = $this->db->result("select * from `wd_data` where `idx`=? and `board_id`=?", array($idx, $this->data->bbs->id));

		$result['options'] = _unserialize($result['options']);
		$result['files'] = _unserialize($result['files']);

		$this->data->bbs->article = $result;
		
		$comment = $this->db->fetch_assoc("select * from `wd_comment` where `data_idx`=? order by `idx` desc", array($idx));
		foreach($comment as $k => $v) {
			$comment[$k]['options'] = _unserialize($v['options']);			
			$comment[$k]['files'] = _unserialize($v['files']);			
		}
		$this->data->bbs->article["comment"] = $comment;
		
	}
	function _getComment( $cidx ) {

		$result = $this->db->result("select * from `wd_comment` where `idx`=?", array($cidx));
		$result['options'] = _unserialize($result['options']);

		$this->data->bbs->comment = $result;

	}

	function useBoard($id, $o = array()) {
		
		// 게시판 기본 처리 부분.

		$this->settings = array_merge($this->settings, $o);

		$mode		= $this->input->get("mode", "list");
		$idx		= (int)$this->input->get("idx", 0);
		$cidx		= (int)$this->input->get("cidx", 0);

		$this->data->bbs->query['mode']		= $mode;
		$this->data->bbs->query['idx']		= $idx;
		$this->data->bbs->query['cidx']		= $cidx; // comment idx;
		
		// 게시판 가져오기.
		$this->_getBoard( $id );

		// post Action
		if ( $this->input->post_exists("action") ) $this->_action(); // Token 체크

		if ($idx !== 0) { // idx값이 있다면?!
			$this->_hitArticle( $idx );
			$this->_getArticle( $idx );
		}
		if ($cidx !== 0) {
			$this->_getComment( $cidx );
		}

		// Token 발행
		$this->data->bbs->token = $_SESSION['wd_token'] = sha1(time()."bs".rand(0,100));

		switch($mode) {
			case "list" :
				$ret = $this->_boardList( $id );
				break;
			case "write" :
				$ret = $this->_boardWrite( $id );
				break;
			case "view" :
				$ret = $this->_boardView( $id );
				break;
			case "modify" :
				$ret = $this->_boardModify( $id );
				break;
			case "delete" :
				$ret = $this->_boardDelete( $id );
				break;
			case "commentdelete" :
				$ret = $this->_boardCommentDelete( $id );
				break;
		}		

		return $ret;
		
	}

	function _boardList($id, $o = array()) {

		if (!$this->data->bbs->is_list) return "error";

		$page 		= (int)$this->input->get("page", 1);
		$category	= (int)$this->input->get("category", 0);
		$search		= $this->input->get("search", null);
		$keyword	= $this->input->get("keyword", null);
		
		$this->data->bbs->query['page']		= $page;
		$this->data->bbs->query['category']	= $category;
		$this->data->bbs->query['search']	= $search;
		$this->data->bbs->query['keyword']	= $keyword;
		
		$len_line = (int)$this->settings['len_line'];
		$len_page = (int)$this->settings['len_page'];
		// pagination
		$where = " where `board_id`='".$this->db->escape($id)."'";
		if ($category !== 0)	$where .= " and `category_idx`='".$this->db->escape($category)."'";
		if ($search == "subject"  || $search == "all") $where .= " and `subject` like '%".$this->db->escape($keyword)."%'";
		if ($search == "contents" || $search == "all") $where .= " and `contents` like '%".$this->db->escape($keyword)."%'";

		$len = $this->db->count("select count(*) from `wd_data`".$where);
		$rows = $this->db->fetch_assoc("select * from `wd_data`".$where." order by `idx` desc limit ".($page-1)*$len_line.", {$len_line}");

		$cnt = count($rows);
		for ($i = 0; $i < $cnt; $i++) {
			$rows[$i]['n']		 = $len - $i - ($page-1)*$len_line;
			$rows[$i]['comment'] = $this->db->count("select count(*) from `wd_comment` where `data_idx`=?", array($rows[$i]['idx']));
			$rows[$i]['options'] = _unserialize($rows[$i]['options']);
			$rows[$i]['files']	 = _unserialize($rows[$i]['files']);
		}
		unset($cnt);

		$pagination = $this->admin->makePagination($len, array(
			"page" => $page,
			"len_line" => $len_line,
			"len_page" => $len_page
		));

		$this->data->bbs->rows = $rows;
		$this->data->bbs->pagination = $pagination;
		
		return "list";	

	}
	
	function _boardWrite($id) {

		if (!$this->data->bbs->is_write) return "error";

		$this->data->bbs->action = "write"; // Action :)

		return "write";	

	}
	
	function _boardView($id) {

		if (!$this->data->bbs->is_view) return "error";
		
		$this->data->bbs->action = "secret"; // Action :)
		
		$ret = "view";
		
		if ( $this->data->bbs->article['secret'] == 1 ) {

			$ret = "secret";

			if ($this->data->bbs->is_secret) $ret = "view";
			
			if ( isset($_SESSION['wd_bbs_recent_secret']) && $_SESSION['wd_bbs_recent_secret'] == $this->data->bbs->query['idx'] ) $ret = "view";

		}
		return $ret;	
	}
	
	function _boardModify($id) {

		if (!$this->data->bbs->is_view) return "error";

		$this->data->bbs->action = "modify"; // Action :)

		$ret = "write";

		if ( $this->data->bbs->article['secret'] == 1 ) {

			$ret = "secret";

			if ( $this->data->bbs->is_modify ) $ret = "write";

			if ( isset($_SESSION['wd_bbs_recent_secret']) && $_SESSION['wd_bbs_recent_secret'] == $this->data->bbs->query['idx'] ) $ret = "write";

		}
		return $ret;	
	}
	function _boardDelete($id) {

		if (!$this->data->bbs->is_write) return "error";

		$this->data->bbs->action = "delete"; // Action :)

		$ret = "delete";

		return $ret;	
	}
	function _boardCommentDelete($id) {

		if (!$this->data->bbs->is_commentwrite) return "error";

		$this->data->bbs->action = "commentdelete"; // Action :)

		$ret = "delete";

		return $ret;	
	}
	
	function _action() {
	
		if ( $this->input->post("token") !== $_SESSION['wd_token'] ) alert("잘못된 접근입니다, 새로고침 후 다시 이용해 주세요.");
		
		$action = $this->input->post("action");
		
		if ( $action == "write" ) {

			if (!$this->data->bbs->is_write) alert("접근권한이 없습니다.");
			
			$member = $this->user;
	
			$board_id		= $this->input->post("board_id");
			$category_idx	= $this->input->post("category");
			$member_idx		= (is_null($member))?0:$member['idx'];
			$writer			= $this->input->post("writer");
			$password		= (is_null($member))?$this->admin->password( $this->input->post("password") ):$member['password'];
			$subject		= $this->input->post("subject");
			$contents		= $this->input->post("contents");
			
			$options = null;
			if ( $this->input->post_exists("options") ) {
				$options			= array();
				$options_list	= explode(",", $this->input->post("options"));
				foreach ($options_list as $v) { $options[$v] = $this->input->post($v); }
				$options			= serialize($options);
			}
			
			$files			= null;
			if ( $this->input->files_exists() ) {
				$this->load->module("files", $this->files);
				$this->files->upload();
				$files = serialize( $this->files->getData() );
			}

			$secret			= $this->input->post("secret");
			$ip				= $_SERVER['REMOTE_ADDR'];
			$dat = array(
				'board_id'		=> $board_id,
				'category_idx'	=> $category_idx,
				'member_idx'		=> $member_idx,
				'writer'		=> $writer,
				'password'		=> $password,
				'subject'		=> $subject,
				'contents'		=> $contents,
				'options'		=> $options,
				'files'			=> $files,
				'secret'		=> $secret,
				'ip'			=> $ip
			);
			try {
				if ( $this->db->insert("wd_data", $dat) === false ) throw new Error("DB를 쓰는 도중 실패하였습니다.");
			}
			catch (Error $e) {echo $e;exit;}
			
			if ( $this->input->post_exists("go") ) go($this->input->post("go"));
		}
		else if ( $action == "modify" ) {
			
			if (!$this->data->bbs->is_view) alert("접근권한이 없습니다.");

			$member = $this->user;

			$idx			= $this->input->post("idx");
			$password		= $this->input->post("password");
			
			$result = $this->db->result("select * from `wd_data` where `idx`=?", array($idx));
			if ( $result['password'] !== $this->admin->password($password) && !$this->data->bbs->is_modify ) alert("비밀번호가 틀렸습니다!");

			$category_idx	= $this->input->post("category");
			$writer			= $this->input->post("writer");
			$subject		= $this->input->post("subject");
			$contents		= $this->input->post("contents");
			
			$options			= array();
			$options_list	= explode(",", $this->input->post("options"));
			foreach ($options_list as $v) { $options[$v] = $this->input->post($v); }
			$options			= serialize($options);
			$secret			= $this->input->post("secret");
			$dat = array(
				'category_idx'	=> $category_idx,
				'writer'		=> $writer,
				'subject'		=> $subject,
				'contents'		=> $contents,
				'options'		=> $options,
				'secret'		=> $secret
			);

			$files			= null;
			if ( $this->input->files_exists() ) {
				$this->load->module("files", $this->files);
				$this->files->upload();
				$files = serialize( $this->files->getData() );
				$dat['files'] = $files;
			}
			
			try {
				if ( $this->db->update("wd_data", $dat, array('idx' => $idx)) === false ) throw new Error("DB를 쓰는 도중 실패하였습니다.");
			}
			catch (Error $e) {echo $e;exit;}
			
			if ( $this->input->post_exists("go") ) go($this->input->post("go"));
		}
		else if ( $action == "delete" ) {
			
			if (!$this->data->bbs->is_write) alert("접근권한이 없습니다.");

			$member = $this->user;

			$idx			= $this->input->post("idx");
			$password		= $this->input->post("password");
			
			$result = $this->db->result("select * from `wd_data` where `idx`=?", array($idx));
			if ( $result['password'] !== $this->admin->password($password) && !$this->data->bbs->is_delete ) alert("비밀번호가 틀렸습니다!");

			
			try {
				if ( $this->db->delete("wd_data", array("idx" => $idx)) === false ) throw new Error("DB를 쓰는 도중 실패하였습니다.");
			}
			catch (Error $e) {echo $e;exit;}
			
			if ( $this->input->post_exists("go") ) go($this->input->post("go"));
		}
		else if ( $action == "commentwrite" ) {

			if (!$this->data->bbs->is_commentwrite) alert("접근권한이 없습니다.");

			$member = $this->user;
	
			$data_idx			= $this->input->post("idx");

			$member_idx		= (is_null($member))?0:$member['idx'];
			$writer			= $this->input->post("writer");
			$password		= (is_null($member))?$this->admin->password( $this->input->post("password") ):$member['password'];
			$contents		= $this->input->post("contents");
			
			$options			= array();
			$options_list	= explode(",", $this->input->post("options"));
			foreach ($options_list as $v) { $options[$v] = $this->input->post($v); }
			$options			= serialize($options);
			$ip				= $_SERVER['REMOTE_ADDR'];

			$dat = array(
				'data_idx'		=> $data_idx,
				'member_idx'	=> $member_idx,
				'writer'		=> $writer,
				'password'		=> $password,
				'contents'		=> $contents,
				'options'		=> $options,
				'ip'			=> $ip
			);
			try {
				if ( $this->db->insert("wd_comment", $dat) === false ) throw new Error("DB를 쓰는 도중 실패하였습니다.");
			}
			catch (Error $e) {echo $e;exit;}
			
			if ( $this->input->post_exists("go") ) go($this->input->post("go"));
		}
		else if ( $action == "commentdelete" ) {

			if (!$this->data->bbs->is_commentwrite) alert("접근권한이 없습니다.");

			$idx			= $this->input->post("cidx"); // 주의!! ㅋㅋ
			$password		= $this->input->post("password");
			
			$result = $this->db->result("select * from `wd_comment` where `idx`=?", array($idx));
			if ( $result['password'] !== $this->admin->password($password) && !$this->data->bbs->is_commentdelete ) alert("비밀번호가 틀렸습니다!");

			if ( $this->db->delete("wd_comment", array("idx" => $idx)) === false ) alert("DB를 쓰는 도중 실패하였습니다.");
			
			if ( $this->input->post_exists("go") ) go($this->input->post("go"));

		}
		else if ( $this->input->post("action") == "secret" ) {
		
			if ( $this->input->post_exists("password") ) {
				
				$result = $this->db->result("select `password` from `wd_data` where `idx`=?", array($this->input->post("idx")));
				if ( $result['password'] == $this->admin->password($this->input->post("password")) ) {
					$_SESSION['wd_bbs_recent_secret'] = $this->data->bbs->query['idx'];
				}
			}
		}
	}
	
	// End Class
	
}
